<template>
    <f7-page>
        <!-- Top Navbar -->
        <f7-navbar>
            <f7-nav-left>
                <f7-link @click="backReturn"
                         icon-material="arrow_back"></f7-link>
            </f7-nav-left>
            <f7-nav-title>起重机械</f7-nav-title>
            <f7-nav-right></f7-nav-right>
        </f7-navbar>
        <div class="preloader-box">
            <div>{{message}}</div>
        </div>
    </f7-page>
</template>

<script>
import controller from "@/libs/framework/controller";
import config from '@/libs/config'
import util from '@/libs/framework/util'
export default class instance extends controller {
    mixin () {
        return {
            data () {
                return {
                    // web应用登录所需参数
                    params: {
                        deviceId: "web",
                        deviceVendor: "Web",
                        deviceName: "Web",
                        deviceNetwork: "Web",
                        osName: window.navigator.platform,
                        osVendor: "Web",
                        osVersion: "",
                        osLanguage: window.navigator.language,
                        appCode: config.info.id,
                        appName: config.info.name,
                        appVersion: config.info.version,
                        needDep: 1,
                    },
                    pageParams: {},// 页面跳转链接携带的参数
                    target: "", // 目标页标识
                    mock: false, // 测试注入
                    message: "正在跳转...",
                }
            },
            async mounted () {
                let _this = this;

                // 1、获取跳转地址中携带的参数
                _this.pageParams = _this.splitUrl();
                // 判断跳转是否带目标页标识，menuCode
                if (!_this.target) {
                    _this.toErr('链接出错，请联系管理员');
                    return;
                }
                for (let i in _this.pageParams) {
                  _this.params[i] = _this.pageParams[i];
                }

                // 5、执行登录操作
                _this.login();
            },
            methods: {
                // 登录请求
                async login () {
                    let _this = this;
                    return new Promise((resolve, reject) => {
                        _this.params.oauthType = "YZ";
                        _this.$framework.account.login(_this.params,
                           (result) => {
                               if (result && result.success) {
                                   // 显示/隐藏导航条
                                   let hidden = _this.target == 'zj_qzjx_home' ? 0 : 1;
                                   //_this.setNavigation(hidden);
                                   // 路由
                                   _this.navigate();
                               } else {
                                   // 清除token
                                   vue.$f7.data.authToken = null;
                                   vue.$f7.data.csrfToken = null;
                                   _this.$framework.account.removeUser();

                                   _this.toErr((result && result.message) ? result.message : '登录失败，请检查网络连接');
                               }
                           }
                       );
                    })
                },
                // 拼接工程编码跳转路径
                getSpiltUrl(url){
                    // let paramStr = [];
                    // for (let key in this.pageParams) {
                    //     paramStr.push(`${key}=${this.pageParams[key]}`);
                    // }
                    // paramStr = paramStr.join("&");
                    // return url+'?'+paramStr
                    if(this.pageParams.gcbm){
                        return `${url}?engineeCode=${this.pageParams.gcbm}`
                    }else{
                        return url
                    }
                },
                // 处理路由
                navigate () {
                    if(this.target == "workflow") {
                        this.goWorkflowTodo();
                    } else if(this.target == "aspTodo") {
                        this.goAspTodo();
                    } else if(this.target == "zj_qzjx_supervisor" || this.target == "zj_qzjx_property") {
                        // this.$f7.views.current.router.navigate('/business/qzjx/equipment/list');
                        this.$f7.views.current.router.navigate(this.getSpiltUrl('/business/qzjx/equipment/list'));
                    } else if(this.target == "zj_qzjx_statistics") {
                        this.$f7.views.current.router.navigate(this.getSpiltUrl('/business/qzjx/statistics/index'));
                    } else {
                        // this.$f7.views.current.router.navigate(config.pages.home);
                        this.$f7.views.current.router.navigate(this.getSpiltUrl(config.pages.home));
                    }
                },
                // 工作流待办处理
                goWorkflowTodo () {
                    let _this = this,
                        formId = _this.pageParams["formId"];
                    _this.getWorkflowArgs({
                        formId: formId
                    }).then((rlt) => {
                        let url = config.pages.home;
                        if (rlt.taskId) {
                            url = `${
                                rlt.mobileFormUrl
                            }?action=processEdit&taskId=${
                                rlt.taskId
                            }&assigneeId=${rlt.assigneeId}&appCode=${
                                rlt.appCode
                            }&version=${
                                rlt.version
                            }&formId=${
                                formId
                            }&_r=${new Date().getTime()}`
                        } else if (rlt.historyTaskId) {
                            url = `${
                                rlt.mobileFormUrl
                            }?action=processView&historyTaskId=${
                                rlt.historyTaskId
                            }&appCode=${rlt.appCode}&version=${
                                rlt.version
                            }&formId=${
                                formId
                            }&_r=${new Date().getTime()}&assigneeId=${
                                rlt.assigneeId
                            }`
                        }
                        console.log(`========== 目标页面地址：${url}`);
                        _this.$f7.views.current.router.navigate(url);
                    }).catch(err => {
                        _this.toErr('查询待办信息失败');
                    });
                },
                // 普通业务待办
                goAspTodo () {
                    let _this = this,
                        id = _this.pageParams["id"];
                    _this.$f7.request.post("/workflow/toDoListExt/getAspTodoArgs",
                        { id: id },
                        rlt => {
                            let url = config.pages.home;
                            if (typeof rlt == "string") {
                                rlt = JSON.parse(rlt);
                            }
                            if(rlt && rlt.success) {
                                let item = rlt.parameters.data;
                                url = rlt.parameters.pageAction == 'edit' ? item.appEditUrl : item.appViewUrl;
                                if(!url) {
                                    url = item.defaultUrl;
                                }
                                url += url.indexOf('?') > -1 ? '&' : '?';
                                url+=`_r=${new Date().getTime()}`
                                /* // 附加参数
                                let thirdParams=JSON.parse(item.thirdParams)
                                // 如果地址上有pageAction，thirdParams也有pageAction，则忽略thirdParams里面的pageAction
                                if(url.indexOf('pageAction')!=-1&&thirdParams.pageAction){
                                    delete thirdParams.pageAction
                                }
                                // 拼接参数
                                let params={
                                    ...thirdParams,
                                    _r:new Date().getTime(),
                                }
                                let paramStr = [];
                                for (let key in params) {
                                    paramStr.push(`${key}=${params[key]}`);
                                }
                                paramStr = paramStr.join("&");
                                // 参数拼接完毕，跟地址拼接跳转
                                url += paramStr */

                            }
                            console.log(`========== 目标页面地址：${url}`);
                            _this.$f7.views.current.router.navigate(url);
                        },
                        err => {
                            _this.toErr('查询待办信息失败');
                        }
                    );
                },
                // 通过元知sdk提供方法获取用户信息  及 获取地址中携带的参数
                getUserToken () {
                    let _this = this;
                    return new Promise((resolve, reject) => {
                        // 提供测试时注入
                        if(_this.mock) {
                            let tokenId = window.localStorage.getItem("mockUserInfo")
                                || "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxNjY0NTYxNjQ4OTI2NTkzMDI0IiwiYWNjb3VudFRva2VuSWQiOjE2NjQ1NjE2NDg5MjY1OTMwMjQsInRva2VuRXhwaXJlc1RpbWUiOjI1OTIwMDAsInRva2VuUmVmcmVzaFRpbWUiOjI1OTIwMDAsImV4cCI6MTY4ODI4OTM5N30.EP9onXyiuWmxNjgiBKUXFKMQLx6oXAk1F7t5ZuVMIQ52pCVNiIGhEjQKjpevxtqiulS1C82JxGwhckFMBfsHrw";
                            resolve(tokenId);
                            return;
                        }
                        umSdk.getSessionStorage({
                            success: function (res) {
                                let result = {};
                                // 用户名，手机号，um的token
                                for (let item in res) {
                                    result[item] = res[item]
                                }
                                resolve(result.tokenId);
                            },
                            fail: function (err) {
                                resolve("");
                            }
                        })
                    })
                },
                // 跳转错误提示页面
                toErr (err) {
                    this.message = err;
                },
                // 截取地址参数
                splitUrl () {
                    let _this = this;
                    let qs = window.location.href.split('?').length > 0 ? window.location.href.split('?')[1] : []
                    let args = {};
                    let items = qs.length ? qs.split('&') : [];
                    let item = null;
                    let name = null;
                    let value = null;
                    for (let i = 0; i < items.length; i++) {
                        item = items[i].split('=');
                        name = decodeURIComponent(item[0]);
                        value = decodeURIComponent(item[1]);
                        if (name.length && name != 'menuCode' && name != 'mock') {
                            args[name] = value
                        }
                        if (name == 'menuCode') {
                            _this.target = value
                        } else if (name == 'mock') {
                            _this.mock = value
                        }
                    };
                    return args;
                },
                setNavigation (hidden) {
                    umSdk.setNavigation({
                        title: "起重机械", // 导航栏标题
                        hidden: hidden, // 0显示导航栏 1隐藏导航栏，默认显示
                        type: 1, // 导航栏类型（1:一级导航，2:二级导航）默认：2
                        success: function () { },
                        fail: function (err) { }
                    });
                },
                backReturn () {
                    window.parent.postMessage({status: true},'*');
                },
            },
        };
    }
}
</script>
<style lang="less" scoped>
.preloader-box {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    align-content: center;
    justify-content: center;
    div {
        text-align: center;
        width: 100%;
        height: 30px;
        line-height: 30px;
        font-size: 16px;
        margin-top: 6px;
    }
}
</style>
